//
//  BanBu_AppDelegate.m
//  BanBu
//
//  Created by jie zheng on 12-7-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BanBu_AppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#import "UIBadgeView.h"
#import "UINavigationBar+TKCategory.h"
#import "BanBu_NavigationController.h"
#import "BanBu_ListViewController.h"
#import "BanBu_MyFriendViewController.h"
#import "BanBu_ChatViewController.h"
#import "BanBu_LocationManager.h"
#import "BanBu_DialogueController.h"
#import "BanBu_MySpaceViewController.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "UIImageView+WebCache.h"
#import "BanBu_BroadcastTVC.h"
#import "LeveyTabBarController.h"
#import "BanBu_ThemeManager.h"
#import "SFHFKeychainUtils.h"
#import "BanBu_TestHostSpeed.h"
#import "CJSONSerializer.h"
#import "CJSONDataSerializer.h"
#import "BanBu_RegisterViewController.h"
#import "BanBu_Remind.h"
#import "BanBu_MagicWordsAPI.h"
#import "UMSocial.h"
#import "UMSocialSinaHandler.h"
#import "UMSocialTencentWeiboHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialRenrenHandler.h"
#import "UMSocialFacebookHandler.h"
#import "UMSocialTwitterHandler.h"


NSString *const SCSessionStateChangedNotification = @"com.halfeet_scrapt:SCSessionStateChangedNotification";

@implementation BanBu_AppDelegate

@synthesize window = _window;
@synthesize tabbarController = _tabbarController;
@synthesize logined = _logined;
@synthesize string=_string;
@synthesize dialogue = dialogue;
- (void)dealloc
{
    self.tokenCaching = nil;
    [_window release];
    [_pushid release];
    [_tabbarController release];
    [super dealloc];
}

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}

void uncaughtExceptionHandler(NSException *exception) {
    //    NSLog(@"CRASH: %@", exception);
    //    NSLog(@"Stack Trace: %@", [exception callStackSymbols]);
    // Internal error reporting
}
#pragma CLLocationManager delegate method
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [UMSocialData setAppKey:@"53d5c27656240b687d01b691"];
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    //  [UMSocialTencentWeiboHandler openSSOWithRedirectUrl:@"http://sns.whalecloud.com/tencent2/callback"];
    [UMSocialQQHandler setQQWithAppId:@"801238036" appKey:@"53d5c27656240b687d01b691" url:@"http://www.halfarea.com"];
    [UMSocialWechatHandler setWXAppId:@"wxdc4067959fdc4c30" appSecret:@"e7b6b1c4eadb5a7b3ea6fc24a922db05" url:nil];
    [UMSocialFacebookHandler setFacebookAppID:@"553993237962801" shareFacebookWithURL:@"http://www.halfarea.com"];
    [UMSocialTwitterHandler openTwitter];
    
    //启动程序时，向微信终端注册id
    [WXApi registerApp:@"wxdc4067959fdc4c30"];
    //    [WXApi registerApp:@"wx4269f4b199ea104b"];
    
    //    NSLog(@"%@",idfaString);
    [self getServerList];
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    if([[UserDefaults valueForKey:@"currentTheme"] length])
    {
        ThemeManager.themeName = [UserDefaults valueForKey:@"currentTheme"];
    }
    else
        ThemeManager.themeName = @"default";
    if([UserDefaults valueForKey:@"downLoadTheme"])
    {
        ThemeManager.themeDown = [UserDefaults valueForKey:@"downLoadTheme"];
    }
    if([UserDefaults valueForKey:@"exitTheme"])
    {
        [ThemeManager.themeExitArr addObjectsFromArray:[UserDefaults valueForKey:@"exitTheme"]];
    }
    if(![FBSession defaultAppID]){
        //        [FBSession setDefaultAppID:@"471677566220485"];
        [FBSession setDefaultAppID:@"195595733947790"];
    }
    //最新系统版本
    MyAppDataManager.newVersionNumber = [UserDefaults valueForKey:@"ios_ver"];
    
    NSString * stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * documentFile = [stringPath stringByAppendingPathComponent:@"one"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:documentFile]) {
        NSDictionary *aDic = [NSDictionary dictionaryWithObjectsAndKeys:@"http://74.117.60.99",@"chatserver",@"http://74.117.60.99",@"database",@"http://74.117.60.99",@"fileupload", nil];
        [UserDefaults setValue:aDic forKey:@"serverlist"];
        
    }
    
    UIApplication *app = [UIApplication sharedApplication];
    [app setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];
    [app setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    
    _logined = NO;
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tabbarController = [[[LeveyTabBarController alloc] init] autorelease];
    
    dialogue = [[BanBu_DialogueController alloc] init] ;
    BanBu_ListViewController *luckPeople = [[[BanBu_ListViewController alloc] init] autorelease];
    BanBu_MyFriendViewController *myFriend = [[[BanBu_MyFriendViewController alloc] init] autorelease];
    BanBu_BroadcastTVC *broadcast = [[[BanBu_BroadcastTVC alloc] initWithStyle:UITableViewStylePlain] autorelease];
    BanBu_MySpaceViewController *mySpace = [[[BanBu_MySpaceViewController alloc] init ] autorelease];
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        mySpace.edgesForExtendedLayout = UIRectEdgeNone;
        mySpace.extendedLayoutIncludesOpaqueBars = NO;
        mySpace.modalPresentationCapturesStatusBarAppearance = NO;
        mySpace.automaticallyAdjustsScrollViewInsets = NO;
        
        broadcast.edgesForExtendedLayout = UIRectEdgeNone;
        broadcast.extendedLayoutIncludesOpaqueBars = NO;
        broadcast.modalPresentationCapturesStatusBarAppearance = NO;
        broadcast.automaticallyAdjustsScrollViewInsets = NO;
        
        myFriend.edgesForExtendedLayout = UIRectEdgeNone;
        myFriend.extendedLayoutIncludesOpaqueBars = NO;
        myFriend.modalPresentationCapturesStatusBarAppearance = NO;
        myFriend.automaticallyAdjustsScrollViewInsets = NO;
        
        luckPeople.edgesForExtendedLayout = UIRectEdgeNone;
        luckPeople.extendedLayoutIncludesOpaqueBars = NO;
        luckPeople.modalPresentationCapturesStatusBarAppearance = NO;
        luckPeople.automaticallyAdjustsScrollViewInsets = NO;
        
        dialogue.edgesForExtendedLayout = UIRectEdgeNone;
        dialogue.extendedLayoutIncludesOpaqueBars = NO;
        dialogue.modalPresentationCapturesStatusBarAppearance = NO;
        dialogue.automaticallyAdjustsScrollViewInsets = NO;
    }
    broadcast.title = NSLocalizedString(@"broadcastTitle", nil);
    
    luckPeople.title = NSLocalizedString(@"luckPeopleTitle", nil);
    //    select.title = NSLocalizedString(@"selectTitle", nil);
    
    dialogue.title = NSLocalizedString(@"dialogueTitle", nil);
    myFriend.title = NSLocalizedString(@"myFriendTitle", nil);
    mySpace.title = NSLocalizedString(@"mySpaceTitle", nil);
    
    BanBu_NavigationController *nav1 = [[[BanBu_NavigationController alloc] initWithRootViewController:luckPeople] autorelease];
    BanBu_NavigationController *nav2 = [[[BanBu_NavigationController alloc] initWithRootViewController:broadcast] autorelease];
    BanBu_NavigationController *nav3 = [[[BanBu_NavigationController alloc] initWithRootViewController:dialogue] autorelease];
    BanBu_NavigationController *nav4 = [[[BanBu_NavigationController alloc] initWithRootViewController:myFriend] autorelease];
    BanBu_NavigationController *nav5 = [[[BanBu_NavigationController alloc] initWithRootViewController:mySpace] autorelease];
    
    NSArray *controllersArr = [NSArray arrayWithObjects:nav1,nav2,nav3,nav4,nav5, nil];
    
    
    NSMutableDictionary *imgDic = [NSMutableDictionary dictionaryWithCapacity:3];
    [imgDic setObject:[ThemeManager getThemeImage:@"nearby.png"] forKey:@"Default"];
    [imgDic setObject:[ThemeManager getThemeImage:@"nearby_selected.png"] forKey:@"Highlighted"];
    [imgDic setObject:[ThemeManager getThemeImage:@"nearby_selected.png"] forKey:@"Seleted"];
    NSMutableDictionary *imgDic2 = [NSMutableDictionary dictionaryWithCapacity:3];
    [imgDic2 setObject:[ThemeManager getThemeImage:@"throwball.png"] forKey:@"Default"];
    [imgDic2 setObject:[ThemeManager getThemeImage:@"throwball_selected.png"] forKey:@"Highlighted"];
    [imgDic2 setObject:[ThemeManager getThemeImage:@"throwball_selected.png"] forKey:@"Seleted"];
    NSMutableDictionary *imgDic3 = [NSMutableDictionary dictionaryWithCapacity:3];
    [imgDic3 setObject:[ThemeManager getThemeImage:@"chat.png"] forKey:@"Default"];
    [imgDic3 setObject:[ThemeManager getThemeImage:@"chat_selected.png"] forKey:@"Highlighted"];
    [imgDic3 setObject:[ThemeManager getThemeImage:@"chat_selected.png"] forKey:@"Seleted"];
    NSMutableDictionary *imgDic4 = [NSMutableDictionary dictionaryWithCapacity:3];
    [imgDic4 setObject:[ThemeManager getThemeImage:@"myfriend.png"] forKey:@"Default"];
    [imgDic4 setObject:[ThemeManager getThemeImage:@"myfriend_selected.png"] forKey:@"Highlighted"];
    [imgDic4 setObject:[ThemeManager getThemeImage:@"myfriend_selected.png"] forKey:@"Seleted"];
    NSMutableDictionary *imgDic5 = [NSMutableDictionary dictionaryWithCapacity:3];
    [imgDic5 setObject:[ThemeManager getThemeImage:@"myapplication.png"] forKey:@"Default"];
    [imgDic5 setObject:[ThemeManager getThemeImage:@"myapplication_selected.png"] forKey:@"Highlighted"];
    [imgDic5 setObject:[ThemeManager getThemeImage:@"myapplication_selected.png"] forKey:@"Seleted"];
    
    NSArray *imgArr = [NSArray arrayWithObjects:imgDic,imgDic2,imgDic3,imgDic4,imgDic5,nil];
    
    
    [_tabbarController initWithViewControllers:controllersArr imageArray:imgArr];
    [_tabbarController setTabBarTransparent:YES];
    _tabbarController.containerView.backgroundColor = [UIColor clearColor];
    _tabbarController.transitionView.backgroundColor = [UIColor clearColor];
    _tabbarController.tabBar.backgroundColor = [UIColor clearColor];
    //    _tabbarController.tabBar.backgroundView  = nil;
    [_tabbarController.tabBar setBackgroundImage:[ThemeManager getThemeImage:@"tabbarImage.png"]];
    NSArray *array = [NSArray arrayWithObjects:
                      NSLocalizedString(@"luckPeopleTitle", nil),NSLocalizedString(@"broadcastTitle", nil),
                      NSLocalizedString(@"dialogueTitle", nil),
                      NSLocalizedString(@"myFriendTitle", nil),
                      NSLocalizedString(@"mySpaceTitle", nil),nil];
    int i = 0;
    for(UIButton *button in self.tabbarController.tabBar.buttons)
    {
        [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal] ;
        [button setTitleEdgeInsets:UIEdgeInsetsMake(ThemeManager.tabbarHeight/2+10, 0, 0, 0)];
        button.titleLabel.textAlignment = kTextAlignmentCenter;
        button.titleLabel.font = [UIFont systemFontOfSize:10];
        button.titleLabel.textColor = [UIColor whiteColor];
        i++;
    }
    
    
    
    [UserDefaults setValue:[NSNumber numberWithInt:0] forKey:@"first"];
    
    if([UserDefaults valueForKey:@"myID"] && [[UserDefaults valueForKey: [UserDefaults valueForKey:@"myID"]] valueForKey:@"loginid"] )
    {
        
        self.numberOfLogin = [[UserDefaults valueForKey:@"numberOfLogin"] integerValue];
        if(self.numberOfLogin==-1)
        {
            self.numberOfLogin = -1;
        }
        else
        {
            if(self.numberOfLogin<100)
                self.numberOfLogin++;
            if(self.numberOfLogin >14 &&self.numberOfLogin <100)
            {
                self.numberOfLogin = -1;
            }
            
            if(self.numberOfLogin==4||self.numberOfLogin == 14)
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"pinglunTitle", nil) message:NSLocalizedString(@"pinglunNotice", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"laterButton", nil) otherButtonTitles:NSLocalizedString(@"newButton",nil), nil];
                alert.tag = 157;
                [alert show];
                [alert release];
            }
            
            [UserDefaults setInteger:self.numberOfLogin forKey:@"numberOfLogin"];
        }
        
        
        
        MyAppDataManager.useruid = [UserDefaults valueForKey:@"myID"];
        MyAppDataManager.loginid = [[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"loginid"];
        MyAppDataManager.appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
        NSLog(@"%@",MyAppDataManager.appVersion);
        
        MyAppDataManager.userAvatar = [[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"uface"];
        _logined = YES;
        
        [self setViewController:YES];
    }
    else
    {
        if(!_logined)
        {
            BanBu_RegisterViewController *unLogin = [[[BanBu_RegisterViewController alloc] init] autorelease];
            BanBu_NavigationController *nav = [[[BanBu_NavigationController alloc] initWithRootViewController:unLogin] autorelease];
            self.window.rootViewController = nav;
        }
        else
        {
            
            self.numberOfLogin = [[UserDefaults valueForKey:@"numberOfLogin"] integerValue];
            if(self.numberOfLogin==-1)
            {
                self.numberOfLogin = -1;
            }
            else
            {
                if(self.numberOfLogin<100)
                    self.numberOfLogin++;
                if(self.numberOfLogin >14 &&self.numberOfLogin <100){
                    self.numberOfLogin = -1;
                }
                if(self.numberOfLogin==4||self.numberOfLogin == 14)
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"pinglunTitle", nil) message:NSLocalizedString(@"pinglunNotice", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"laterButton", nil) otherButtonTitles:NSLocalizedString(@"newButton",nil), nil];
                    alert.tag = 157;
                    [alert show];
                    [alert release];
                }
                
                [UserDefaults setInteger:self.numberOfLogin forKey:@"numberOfLogin"];
            }
            
            self.window.rootViewController = self.tabbarController;
        }
    }
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
    
    if(![MyAppDataManager.newVersionNumber isEqual:version]&&MyAppDataManager.newVersionNumber.length)
    {
        [_tabbarController.tabBar setBadgeValue:@"N" withButtonIndex:4];
    }
    
    [self.window makeKeyAndVisible];
    
    
    
    if(MyAppDataManager.useruid.length)
    {
        [MyAppDataManager.unReadBroadInfor addEntriesFromDictionary:[MyAppDataManager getUserBaseDataWithKey:KeyUnReadDynamicNum]];
        //        NSString *badgeValue = [NSString stringWithFormat:@"%d",[[MyAppDataManager.unReadBroadInfor valueForKey:@"g"] integerValue]+[[MyAppDataManager.unReadBroadInfor valueForKey:@"h"] integerValue]+[[MyAppDataManager.unReadBroadInfor valueForKey:@"z"] integerValue]];
        //        [self.tabbarController.tabBar setBadgeValue:badgeValue withButtonIndex:1];
        NSInteger unReadNum = [[MyAppDataManager.unReadBroadInfor valueForKey:@"g"] integerValue]+[[MyAppDataManager.unReadBroadInfor valueForKey:@"h"] integerValue]+[[MyAppDataManager.unReadBroadInfor valueForKey:@"z"] integerValue];
        BOOL i = unReadNum>0;
        [self.tabbarController.tabBar setTabBarNoticeView:i withButtonIndex:1];
    }
    
    
    application.applicationIconBadgeNumber = 0;
    
    // IOS8 新系统需要使用新的代码咯
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        //这里还是原来的代码
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge |
          UIRemoteNotificationTypeAlert |
          UIRemoteNotificationTypeSound)];
    }
    
    
    
    return YES;
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    //2014年09月28日09:29:41 yinlinlin ios8推送问题
    self.pushid = [NSString stringWithFormat:@"%@",deviceToken];
    [AppComManager getBanBuData:BanBu_Set_My_Pushid par:[NSDictionary dictionaryWithObject:self.pushid forKey:@"pushid"] delegate:nil];
    [UserDefaults setValue:self.pushid forKey:@"pushid"];
    
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    [UserDefaults setValue:@"" forKeyPath:@"pushid"];
    [UserDefaults synchronize];
    NSLog(@"Failed to get token, error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    
}

- (void)goToLogin:(NSString *)detailMsg
{
    //    [AppComManager.receiveMsgQueue cancelAllOperations];
    
    [AppComManager.receiveMsgTimer invalidate];
    AppComManager.receiveMsgTimer = nil;
    [AppComManager stopReceiveMsgForUid:nil];
    if(!_logined)
    {
        return;
    }
    
    [self setViewController:NO];
    if(!_isFirstVaild){
        _isFirstVaild = !_isFirstVaild;
        
        
        if([AppComManager.receiveMsgTimer isValid])
        {
            [AppComManager.receiveMsgTimer invalidate];
            
            AppComManager.receiveMsgTimer=nil;
        }
        [AppComManager stopReceiveMsgForUid:nil];
        [AppComManager.receiveMsgQueue cancelAllOperations];
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:[UserDefaults valueForKey:[UserDefaults valueForKey:@"myID"]]];
        [dic removeObjectForKey:@"loginid"];
        [MyAppDataManager.talkPeoples removeAllObjects];
        [MyAppDataManager.secondaryTalkPeople removeAllObjects];
        [MyAppDataManager.dialogs removeAllObjects];
        
        MyAppDataManager.useruid = @"";
        [UserDefaults setObject:dic forKey:[UserDefaults valueForKey:@"myID"]];
        [UserDefaults synchronize];
        //    [UserDefaults removeObjectForKey:@"loginid"];
        [dic release];
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        [parDic setValue:@"apple" forKey:@"server"];
        [parDic setValue:@"" forKey:@"pushid"];
        [AppComManager getBanBuData:Banbu_Set_User_Pushid par:parDic delegate:self];
        
        AppComManager.isReceivingDialods = NO;
        
        UIAlertView *jidiaole = [[UIAlertView alloc]initWithTitle:detailMsg message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles:nil];
        [jidiaole show];
        [jidiaole release];
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 157)
    {
        if(buttonIndex == 1)
        {
            NSString *stringURL = @"https://itunes.apple.com/us/app/halfarea-free-online-chat/id919437367?l=zh&ls=1&mt=8";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringURL]];
            [UserDefaults setInteger:100 forKey:@"numberOfLogin"];
            
        }
    }
    
    _isFirstVaild = NO;
    
    
}

#pragma mark - 登陆成功或者退出登录，切换显示界面
- (void)setViewController:(BOOL)login
{
    [UserDefaults setValue:[NSNumber numberWithInt:0] forKey:@"first"];
    
    _logined = login;
    
    id visibleController = nil;
    if(login)
    {
        //重新设置密码的提示
        [BanBu_Remind modifyPasswordPromptTitle:NSLocalizedString(@"setPasswordTitle", nil) Detail:NSLocalizedString(@"setPasswordDetail",nil) Type:RemindTypeModifyPassword goBlock:^{
            //        NSLog(@"确定");
        } cancelBlock:^{
            //        NSLog(@"取消");
        }];

        self.tabbarController.isFirstIn = YES;
        self.tabbarController.selectedIndex = 0;
        
        visibleController = self.tabbarController;
        
        [MyAppDataManager readTalkList:nil WithNumber:0];
        
        [AppComManager startReceiveMsgFromUid:nil forDelegate:MyAppDataManager];
        
        [self updateBadge];
    }
    else
    {
        if([AppComManager.receiveMsgTimer isValid])
        {
            [AppComManager.receiveMsgTimer invalidate];
            
            AppComManager.receiveMsgTimer=nil;
            
        }
        
        BanBu_RegisterViewController *unLogin = [[[BanBu_RegisterViewController alloc] init] autorelease];
        BanBu_NavigationController *nav = [[[BanBu_NavigationController alloc] initWithRootViewController:unLogin] autorelease];
        visibleController = nav;
    }
    
    CATransition *animation = [CATransition animation];
    animation.duration = .5f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFade;
    self.window.rootViewController = visibleController;
    [self.window.layer addAnimation:animation forKey:@"animation"];
    
    
}

- (void)updateBadge
{
    [dialogue updateBadgeShow];
}



-(void)updateDialoge:(NSString *)str
{
    if([str intValue]==0)
        return;
    UINavigationController *nav = [_tabbarController.viewControllers objectAtIndex:4];
    BanBu_MySpaceViewController *diavc = nil;
    for(BanBu_MySpaceViewController *dia in nav.viewControllers)
    {
        if([dia isMemberOfClass:[BanBu_MySpaceViewController  class]])
        {
            diavc = dia;
            break;
        }
    }
    
    
    [diavc createTheBandageView:str];
    
    
}





#pragma mark - WXApiDelegate

//-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
//    NSLog(@"%@",sourceApplication);
//    return [WXApi handleOpenURL:url delegate:self];
//}
-(void) onRequestAppMessage
{
    // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
    
    
}

-(void) onReq:(BaseReq*)req
{
    //    NSLog(@"%d",req.type);
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        [self onRequestAppMessage];
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        //        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        //        [self onShowMediaMessage:temp.message];
    }
    
    
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        
        if(resp.errCode == 0){
            
            [TKLoadingView showTkloadingAddedTo:self.window title:NSLocalizedString(@"shareSuccess", nil) activityAnimated:NO duration:2.0];
            
        }else if(resp.errCode == -2){
            
            [TKLoadingView showTkloadingAddedTo:self.window title:NSLocalizedString(@"errcode_cancel", nil) activityAnimated:NO duration:2.0];
        }
    }
    //    else if([resp isKindOfClass:[SendAuthResp class]])
    //    {
    //        //        NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
    //        //        NSString *strMsg = [NSString stringWithFormat:@"Auth结果:%d", resp.errCode];
    //        //
    //        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    //        //        [alert show];
    //        //        [alert release];
    //    }
}

-(void)saveLastTime
{
    
    MyAppDataManager.deep=NO;
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *stime = [formatter stringFromDate:[NSDate date]];
    
    [UserDefaults setValue:stime forKey:@"lasttime"];
    
}




- (void)applicationWillResignActive:(UIApplication *)application
{
    
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    if(MyAppDataManager.useruid)
    {
        //有选择气泡、背景的情况，按home后要先存起来选择的选项
        [UserDefaults setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBgIndex] forKey:@"selectedBgIndex"];
        [UserDefaults setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex] forKey:@"selectedBubbleIndex"];
        //将接收到一般的消息存起来
        if (AppComManager.mutableData.length>0)
        {
            NSString * msgFilePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"msgMata"];
            [AppComManager.mutableData writeToFile:msgFilePath atomically:YES];
        }
        
        
        [self saveLastTime];
        NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
        
        if([uidDic valueForKey:@"loginid"])
        {
            NSInteger total = 0;
            
            total = [MyAppDataManager getBadgeValue];
            
            application.applicationIconBadgeNumber  = total;
        }
        else
        {
            application.applicationIconBadgeNumber  = 0;
        }
    }
    
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    [parDic setValue:self.pushid forKey:@"pushid"];
    [parDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [parDic setValue:[NSNumber numberWithInt:application.applicationIconBadgeNumber] forKey:@"pushcount"];
    [AppComManager getBanBuData:BanBu_Set_Myphone_Offline par:parDic delegate:nil];
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    application.applicationIconBadgeNumber = 0;
    
    // IOS8 新系统需要使用新的代码咯
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge |
          UIRemoteNotificationTypeAlert |
          UIRemoteNotificationTypeSound)];
    }    [self.tabbarController viewDidAppear:YES];
    
    [self interandword];
    [AppLocationManager getLocation];
    [[FBSession activeSession] handleDidBecomeActive];
    if([AppComManager.receiveMsgTimer isValid])
    {
        [AppComManager.receiveMsgTimer invalidate];
        
        AppComManager.receiveMsgTimer=nil;
    }
    
    MyAppDataManager.selectedBgIndex = [[UserDefaults valueForKey:@"selectedBgIndex"] integerValue];
    MyAppDataManager.selectedBubbleIndex = [[UserDefaults valueForKey:@"selectedBubbleIndex"] integerValue];
    
    //处理上次接收到一半的消息
    NSString * msgFilePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"msgMata"];
    AppComManager.mutableData = [NSMutableData dataWithContentsOfFile:msgFilePath];
    
    if (AppComManager.mutableData.length > 0)
    {
        [[NSFileManager defaultManager]removeItemAtPath:msgFilePath error:nil];
    }
    if(_logined)
    {
        [AppComManager receiveMsgFromUser:MyAppDataManager.chatuid delegate:MyAppDataManager];
    }
    
    //如果是对话界面
    if (self.tabbarController.selectedIndex == 2)
    {
        [self updateBadge];
    }
}


- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[FBSession activeSession] close];
    
}

-(void)interandword{
    // 序列化存储各种数据
    //判断有没有这么一个文件 并且判断有没有超过三十天
    // 获取当前时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    
    NSDate *miniDate = [formatter dateFromString:dateStr];
    NSDate *beforeDate=[formatter dateFromString:[UserDefaults valueForKey:@"badwordtime"]];
    
    NSTimeInterval time=[miniDate timeIntervalSinceDate:beforeDate];
    
    int days=((int)time)/(3600*24);
    // 这是国际语言包
    
    NSDate *languageDate=[formatter dateFromString:[UserDefaults valueForKey:@"internationalTime"]];
    NSTimeInterval time2=[miniDate timeIntervalSinceDate:languageDate];
    int languageDays=((int)time2)/(3600*24);
    
    [formatter release];
    
    /*
     // 这是不文明用语的路径
     NSString  *path1 =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"BadWord"];
     // 这是判断不文明用语
     if(![FileManager fileExistsAtPath:path1]||days>=30)
     {
     NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
     
     [AppComManager getBanBuData:BanBu_BadWordto_check par:loginDic delegate:self];
     }
     else
     {
     NSString *str=[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:path1]];
     MyAppDataManager.blackString=str;
     }
     */
    
    // 这是国际语言包的路径
    NSString  *path2 =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"InterNationalanguage"];
    
    NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
    [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    
    // 这是国际用语
    if(![FileManager fileExistsAtPath:path2]||languageDays>=1)
    {
        NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
        [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
        [AppComManager getBanBuData:BanBu_Internationar_Language par:loginDic delegate:self];
        
        //下载破冰语热门关键词
        [AppComManager getBanBuData:BanBu_Get_Sayhi_Hot par:loginDic delegate:self];
        
        //下载彩蛋关键词zip文件url和版本信息
        [AppComManager getBanBuData:BanBu_getKeyword_eggList par:loginDic delegate:self];
        
        //下载收藏的表情信息
        [AppComManager getBanBuDataWIthCollectEmo:BanBu_GetCollectEmo_ByUser par:loginDic delegate:MyAppDataManager];
    }
    else
    {
        [MyAppDataManager.languageDictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:path2]]];
    }
}


- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    if(error)
    {
        // 这是不文明用语的路径
        //        NSString  *path1 =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"BadWord"];
        
        // 这是国际语言包的路径
        NSString  *path2 =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"InterNationalanguage"];
        
        //        if([FileManager fileExistsAtPath:path1])
        //        {
        //            NSString *str=[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:path1]];
        //            MyAppDataManager.blackString=str;
        //
        //        }
        
        if([FileManager fileExistsAtPath:path2])
        {
            
            [MyAppDataManager.languageDictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:path2]]];
            //    NSLog(@"i i i%@",MyAppDataManager.languageDictionary);
        }
        
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            //            [TKLoadingView showTkloadingAddedTo:self.window title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            //            [TKLoadingView showTkloadingAddedTo:self.window title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        
        
        return;
    }
    
    /*
     if([AppComManager respondsDic:resDic isFunctionData:BanBu_BadWordto_check])
     {
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
     NSString *dateStr = [formatter stringFromDate:[NSDate date]];
     [formatter release];
     
     [UserDefaults setValue:dateStr forKey:@"badwordtime"];
     
     [UserDefaults synchronize];
     
     MyAppDataManager.dateString=dateStr;
     MyAppDataManager.blackString=[resDic objectForKey:@"list"];
     
     __block typeof(MyAppDataManager)blockDataManager = MyAppDataManager;
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     dispatch_async(queue, ^{
     
     NSData *listData=[NSKeyedArchiver archivedDataWithRootObject:blockDataManager.blackString];
     
     NSString  *path1 =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"BadWord"];
     
     // NSString *path = [DataCachePath stringByAppendingPathComponent:@"listdata"];
     
     [listData writeToFile:path1 atomically:YES];
     
     });
     
     }
     // 判断一下 是不是国际语言包
     else
     */
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Internationar_Language])//度武器多语言
    {
        //        //NSLog(@"%@",resDic);
        
        [MyAppDataManager.languageDictionary setValue:resDic forKey:@"language"];
        
        //    NSLog(@"*****************%@",MyAppDataManager.languageDictionary);
        //是否显示获取Android设备邀请码
        if([[[resDic valueForKey:@"system_set"]valueForKey:@"get_invite_code"]isEqual:@"y"])
        {
            MyAppDataManager.hidecell = @"1";
            [UserDefaults setValue:MyAppDataManager.hidecell forKey:@"hidecell"];
            [UserDefaults synchronize];
        }
        else
        {
            MyAppDataManager.hidecell = @"0";
            [UserDefaults setValue:MyAppDataManager.hidecell forKey:@"hidecell"];
            [UserDefaults synchronize];
        }
        
        //系统最新版本获取
        MyAppDataManager.newVersionNumber = [resDic valueForKey:@"ios_ver"];
        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
        if(![MyAppDataManager.newVersionNumber isEqual:version]&&MyAppDataManager.newVersionNumber.length)
        {
            [_tabbarController.tabBar setBadgeValue:@"N" withButtonIndex:4];
        }
        [UserDefaults setValue:[resDic valueForKey:@"ios_ver"] forKey:@"ios_ver"];
        
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
        [formatter release];
        
        // 把上一次的网络解析
        
        [UserDefaults setValue:dateStr forKey:@"internationalTime"];
        
        [UserDefaults synchronize];
        
        //        MyAppDataManager.LanguageDateString=dateStr;
        
        // 把获取到的数据存入到文件当中去
        __block typeof(MyAppDataManager)blockDataManager = MyAppDataManager;
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            
            NSData *listData=[NSKeyedArchiver archivedDataWithRootObject:blockDataManager.languageDictionary];
            
            NSString  *path1 =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"InterNationalanguage"];
            
            // NSString *path = [DataCachePath stringByAppendingPathComponent:@"listdata"];
            
            [listData writeToFile:path1 atomically:YES];
            
            
        });
        
        
        
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Server_List])//服务器列表
    {
        if([resDic valueForKey:@"ok"])
        {
            [MyAppDataManager.banbuHostIP setString:@""];
            [MyAppDataManager.banbuHostIP appendString:[NSString stringWithFormat:@"http://%@",[[resDic valueForKey:@"list"] objectAtIndex:0]]];
            [UserDefaults setValue:MyAppDataManager.banbuHostIP forKey:lastHostIP];
            NSLog(@"%@",[UserDefaults valueForKey:lastHostIP]);
            
            
            
            //未读消息数量
            NSInteger total = 0;
            for(NSDictionary *aTalk in MyAppDataManager.talkPeoples)
            {
                total += [VALUE(KeyUnreadNum, aTalk) integerValue];
            }
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",total],@"pushcount",nil];
            [AppComManager getBanBuData:Banbu_Set_User_Pushcount par:dic delegate:self];
            
            //            NSMutableArray *arr = [NSMutableArray arrayWithArray:[resDic valueForKey:@"list"]];
            //            BanBu_TestHostSpeed *test = [[BanBu_TestHostSpeed alloc] initWithHostList:arr];
            //            [test readyTestHostSpeed];
            //            [test release];
            
            //下载版本信息
            NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
            [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            
            [AppComManager getBanBuData:Banbu_Get_ALLVersion par:loginDic delegate:self];
            
            //下载收藏的表情信息
            [AppComManager getBanBuDataWIthCollectEmo:BanBu_GetCollectEmo_ByUser par:loginDic delegate:MyAppDataManager];
            
            //移除之前的收藏数据，换另外方法存储
            [NSKeyedArchiver archiveRootObject:nil toFile:CollectedAmsgInfoPath];
            
            [AppComManager getBanBuDataWIthCollectEmo:BanBu_Get_MagicChatSystemList par:loginDic delegate:MyAppDataManager];
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Sayhi_Hot])//聊天助手关键词
    {
        NSMutableArray *textArr = [[NSMutableArray alloc]initWithCapacity:10];
        NSMutableArray *imageArr = [[NSMutableArray alloc]initWithCapacity:10];
        NSMutableArray *voiceArr = [[NSMutableArray alloc]initWithCapacity:10];
        
        for(NSString *nameAndTypeStr in [resDic objectForKey:@"list"])
        {
            NSArray *separateArr = [nameAndTypeStr componentsSeparatedByString:@"-"];
            NSString *lastStr = [separateArr objectAtIndex:1];
            if([lastStr isEqualToString:@"0"])
            {
                [textArr addObject:[separateArr objectAtIndex:0]];
            }
            else if([lastStr isEqualToString:@"1"])
            {
                [imageArr addObject:[separateArr objectAtIndex:0]];
            }
            else if([lastStr isEqualToString:@"2"])
            {
                [voiceArr addObject:[separateArr objectAtIndex:0]];
            }
        }
        NSArray *  hotKeyArr = [NSArray arrayWithObjects:textArr,imageArr,voiceArr, nil];
        NSDictionary * newHotDict = [NSDictionary dictionaryWithObjectsAndKeys:hotKeyArr,@"hotKeyArr",[MyAppDataManager getPreferredLanguage],@"language", nil];
        [BanBu_CommUtils setLocalData:newHotDict key:HotKeyWordKey];
        //        // 把获取到的数据存入到文件当中去
        //        __block typeof(hotKeyArr)blockhotKeyArr = [hotKeyArr retain];
        //
        //        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //        dispatch_async(queue, ^{
        //            NSData *listData=[NSKeyedArchiver archivedDataWithRootObject:blockhotKeyArr];
        //
        //            NSString  *path1 =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"hotKey"];
        //
        //            [listData writeToFile:path1 atomically:YES];
        //        });
        
        [textArr release];
        [imageArr release];
        [voiceArr release];
    }
    else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_getKeyword_eggList])//彩蛋url和版本信息
    {
        NSString * eggVerson = [UserDefaults valueForKey:@"eggVerson"];
        if (eggVerson == nil)
        {
            eggVerson = @"";
        }
        NSString * newVerson = [[resDic valueForKey:@"list"] valueForKey:@"version"];
        if (newVerson == nil)
        {
            newVerson = @"";
        }
        
        if (![eggVerson isEqualToString:newVerson])//旧版本与新版本不同，可以下载新版本
        {
            //下载新版本彩蛋包
            [AppComManager downLoadEggsWithUrl:[[resDic valueForKey:@"list"] valueForKey:@"eggpath"] withSaveName:@"PaintedEggshellFolder" delegate:nil];
        }
        
        //保存彩蛋包版本信息
        [UserDefaults setValue:newVerson forKey:@"eggVerson"];
    }
    else if ([AppComManager respondsDic:resDic isFunctionData:Banbu_Get_ALLVersion])//获取版本信息
    {
        NSLog(@"resDic:%@",resDic);
        NSDictionary * versionDic= [resDic valueForKey:@"version"];
        NSMutableDictionary * versionBoolDic = [NSMutableDictionary dictionaryWithCapacity:8];
        
        if (versionDic)
        {
            NSDictionary * oldVersion = [UserDefaults valueForKey:@"versionInfo"];
            
            for (NSString * key in versionDic.allKeys)
            {
                if (![[oldVersion valueForKey:key] isEqualToString:[versionDic valueForKey:key]])
                {
                    [versionBoolDic setValue:[NSNumber numberWithBool:YES] forKey:key];
                    if ([key isEqualToString:@"facestore_ver"])
                    {
                        [UserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"hiddenNew"];
                    }
                }
                else
                {
                    [versionBoolDic setValue:[NSNumber numberWithBool:NO] forKey:key];
                }
            }
            
            [UserDefaults setValue:versionBoolDic forKey:@"versionBoolInfo"];
            [UserDefaults setValue:versionDic forKey:@"versionInfo"];
            
            
            [UserDefaults synchronize];
        }
    }
}

+ (NSString *)FBErrorCodeDescription:(FBErrorCode) code {
    switch(code){
        case FBErrorInvalid :{
            return @"FBErrorInvalid";
        }
        case FBErrorOperationCancelled:{
            return @"FBErrorOperationCancelled";
        }
        case FBErrorLoginFailedOrCancelled:{
            return @"FBErrorLoginFailedOrCancelled";
        }
        case FBErrorRequestConnectionApi:{
            return @"FBErrorRequestConnectionApi";
        }case FBErrorProtocolMismatch:{
            return @"FBErrorProtocolMismatch";
        }
        case FBErrorHTTPError:{
            return @"FBErrorHTTPError";
        }
        case FBErrorNonTextMimeTypeReturned:{
            return @"FBErrorNonTextMimeTypeReturned";
        }
            //        case FBErrorNativeDialog:{
            //            return @"FBErrorNativeDialog";
            //        }
        default:
            return @"[Unknown]";
    }
}
#pragma mark - 获取服务器列表
-(void)getServerList
{
    [AppComManager getBanBuData:BanBu_Get_Server_List par:nil delegate:self];
}

@end
